第2页:循环入门
作者:Thau!
有时你想反复做同一件事。你想向某些人询问一个口令,你不断地问,直到得到正确的口令。如果你只想给他们两次尝试的机会,你可以这么做:

var the_password = "pass the wrench";

var answer = prompt("What's the woyd?","");

if (answer != the_password) {

	answer = prompt("What's the woyd?","");

	if (password != the_password) {

		document.write("You lose!<p>");

	} else {

		document.write("That's right!<p>");

	}

} else {

	document.write("That's right!<p>");

}

 

 

不幸的是如果你想不住地问直到得到正确答案,上述做法是不起作用的。假使你是想询问四次而不是两次,那这已经是很讨厌的事了。你将使用四个层次的if-then 子句,这决不是件好事。

反复做相似的事情的最好方法是使用一个循环(loop)。在这种情况下,你可以用一个循环来不断的要求口令直到这个人说出为止。这里有一个while循环工作的例子,口令是:pass the wrench.

1: 第四课介绍
2: 循环介绍
3: 循环的密码
4: 再谈WHILE循环
5: For 循环
6: 嵌套循环
7: 循环练习
8: 数组
9: 数组和循环
10:文件目标模块中的数组
11: 函数
12: 无参数函数
13: 参数及返回值
14: 多于一个参数的函数